package a09_贪心算法;

import java.util.Arrays;

/**
 * <p>
 * a09_K次取反后最大化的数组和
 * </p>
 *
 * @author flyduck
 * @since 2025/1/10
 */
public class a09_K次取反后最大化的数组和 {

    public static void main(String[] args) {
        a09_K次取反后最大化的数组和 test = new a09_K次取反后最大化的数组和();
        System.out.println(test.largestSumAfterKNegations(new int[]{4,2,3}, 1));
    }

    public int largestSumAfterKNegations(int[] nums, int k) {
        Arrays.sort(nums);
        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
            if(nums[i] < 0 && k > 0){
                nums[i] = nums[i] * -1;
                k--;
            }
        }

        Arrays.sort(nums);
        while (k > 0) {
            nums[0] = nums[0 ]* -1;
            k--;
        }
        for (int i = 0; i < nums.length; i++) {
            sum = sum + nums[i];
        }
        return sum;
    }
}
